package com.platform.server.controller;

import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.*;
import com.pingplusplus.model.Transfer;
import com.platform.server.common.Constant;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.entity.Order;
import com.platform.server.entity.Withdraw;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.ServerService;
import com.platform.server.util.AuroraPush;
import com.platform.server.util.PingCons;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

@Component("AutoTask")
public class AutoTask {

    @Autowired
    private ServerDao serverDao;

    @Autowired
    private UserDao userDao;
    @Autowired
    private ServerService serverService;

    /**
     * 时间调度  每天中午12点执行 11/*-*-
     */
    @Scheduled(cron = "0 0 12 * * ?")
    @Transactional
    public void selectMessageTime() throws ParseException {
        //查看用户的生日
        List<Map<String, Object>> birthdays = serverDao.selectUserBirthday();
        for (int i = 0; i < birthdays.size(); i++) {
            Date date = (Date) birthdays.get(i)
                    .get("birthday");
            if (date.getTime() < System.currentTimeMillis()) {
                //修改用户年龄
                Integer age = Integer.valueOf(birthdays.get(i)
                        .get("age")
                        .toString()) + 1;
                serverDao.updateUserAge((Integer) birthdays.get(i)
                        .get("id"), age);
            }
        }

        List<Map<String, Object>> lists = serverDao.selectOrderStatus();
        for (int i = 0; i < lists.size(); i++) {
            Date date = (Date) lists.get(i)
                    .get("create_time");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            // add方法中的第二个参数n中，正数表示该日期后n天，负数表示该日期的前n天
            calendar.add(Calendar.DATE, 5);
            Long newTime = calendar.getTimeInMillis();        //五天后的时间
            Long nowTime = new Date().getTime();            //现在的时间
            if (nowTime > newTime) {
                //修改订单状态为已完成
                serverDao.updateOrderStatu2((Integer) lists.get(i)
                        .get("id"));
            }
        }
    }

    /**
     * 时间调度  每隔5秒钟执行
     */
    @Scheduled(fixedRate = 10000)
    @Transactional
    public void autoExecute() {

    /*	List<Map<String,Object>> selectUserArrearage = serverDao.selectUserArrearage();
    	for (Map<String, Object> map : selectUserArrearage) {
    		 Map<String, Object> map1 = serverDao.selectUserMoney(map.get("user_id").toString());
            Double money = (Double) map1.get("money");
            Map<String, Object> map2 = serverDao.selectUserMoney(map.get("defaulter_id").toString());
            Double money2 = (Double) map2.get("money");
            if (money2 >= 30) {
            	 String s1 = userDao.selectUserMoney("1");
                 serverDao.returnUserMoney(map.get("user_id").toString(), money+30+"");
                 serverDao.insertCancelOrder(map.get("user_id").toString(), "30", "服务方违约金收入", map.get("order_id").toString(),money+30 + "", Constant.INCOME, s1, null);
                 Double money3 = money2 - 30;
                 serverDao.returnUserMoney(map.get("defaulter_id").toString(), money3.toString());
                 serverDao.insertCancelOrder(map.get("defaulter_id").toString(), "30", "服务违约支出", map.get("order_id").toString(), money3 + "", Constant.INCOME, s1, null);
                 serverDao.deleteArrearage(map.get("id").toString());	
            }
		}*/
    	
    	
        //查看超过结束时间两小时未确认完成的订单
        List<Map<String, Object>> selectUserOrderEnd = serverDao.selectUserOrderEnd();
        for (Map<String, Object> map : selectUserOrderEnd) {
            serverService.demandSure(Integer.parseInt(map.get("server_id").toString()), Integer.parseInt(map.get("id").toString()));
        }
        //查看超过两小时未开始服务的订单
        List<Map<String, Object>> selectNoSercerOrder = serverDao.selectNoSercerOrder();
        for (Map<String, Object> map : selectNoSercerOrder) {
            Map<String, Object> map1 = serverDao.selectUserMoney("1");
            String platform_money = map1.get("money")
                    .toString();
            Map<String, Object> selectUserMoney = serverDao.selectUserMoney(map.get("server_user_id").toString());
            //查看用户余额
            Map<String, Object> selectUserMoney2 = serverDao.selectUserMoney(map.get("user_id").toString());
            Double money2 = (Double) selectUserMoney2.get("money");
            Double realityMoney = Double.parseDouble(map.get("reality_price").toString()) + money2;
            // 先把订单的钱退回
            serverDao.returnUserMoney(map.get("user_id").toString(), realityMoney.toString());
            String s = userDao.selectUserMoney("1");

            serverDao.insertCancelOrder(map.get("user_id").toString(), map.get("reality_price").toString(), "预付返还", map.get("order_id").toString(), realityMoney + "", Constant.INCOME, Double.valueOf(s) - Double.valueOf(map.get("reality_price").toString()) + "", null);
            serverDao.returnUserMoney("1",  Double.valueOf(s) - Double.valueOf(map.get("reality_price").toString())+ "");
            Double money = (Double) selectUserMoney.get("money");
            if (money >= 30d) {

                serverDao.insertCancelOrder(map.get("server_user_id").toString(), "30", "服务违约支出", map.get("order_id").toString(), Double.valueOf(money) - Double.valueOf(30) + "", Constant.EXPEND, platform_money, null);
                serverDao.returnUserMoney(map.get("server_user_id").toString(), Double.valueOf(money) - Double.valueOf("30") + "");

                serverDao.insertCancelOrder(map.get("user_id").toString(), "30", "服务方违约金收入", map.get("order_id").toString(), realityMoney + Double.valueOf(30)+ "", Constant.INCOME, platform_money, null);
                serverDao.returnUserMoney(map.get("user_id").toString(), realityMoney + Double.valueOf("30") + "");
            } else {
                // 或者新增违约金记录 （用于充值的时候进行扣除）
                serverDao.insertViolate(30.00, map.get("server_user_id").toString(), map.get("order_id").toString(), map.get("user_id").toString());
            }

            serverDao.cancelOrder(Integer.parseInt(map.get("id").toString()));
        }
        //查看两小时内未确认完成的订单
        List<Map<String, Object>> list = serverDao.selectUnfinishedOrder();
        for (int i = 0; i < list.size(); i++) {
            Date date = (Date) list.get(i)
                    .get("submit_time");
            if (date.getTime() < System.currentTimeMillis()) {
                //修改订单状态为待评价
              /*  serverDao.updateOrderIsRemain((Integer) list.get(i)
                        .get("id"));*/
                //查看订单详情
                Order order = serverDao.selectOrderInfo((Integer) list.get(i)
                        .get("id"));
                serverService.demandSure(Integer.parseInt(order.getServer_id()), Integer.parseInt(list.get(i).get("id").toString()));

               /* String server_user_id = order.getServer_user_id();
                Double sum_price = Double.parseDouble(order.getSum_price());
                Double money = 0D;
                //查看平台手续费
                DecimalFormat df = new DecimalFormat("######0.00");
                Double discount = serverDao.selectPlatformDiscount();
                if (discount > 0) {
                    money = Double.parseDouble(df.format(sum_price * (discount / 100)));
                }
                // 平台余额
                Map<String, Object> map2 = serverDao.selectUserMoney("1");
                String platform_money = map2.get("money")
                        .toString();
                Double _money = sum_price - money;
                //加入服务者余额
                Map<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("user_id", server_user_id);
                hashMap.put("money", _money);
                serverDao.updateServerUserMoney(hashMap);
                Map<String, Object> map1 = serverDao.selectUserMoney(server_user_id);
                String money1 = map1.get("money")
                        .toString();
                serverDao.insertCancelOrder(server_user_id, _money + "", "完成", order.getOrder_id(), Double.valueOf(money1) + _money + "", Constant.INCOME, Double.valueOf(platform_money) - _money + "", sum_price - _money + "");
                serverDao.returnUserMoney("1", Double.valueOf(platform_money) - (sum_price - money) + "");*/

            }
        }

        //查看需求列表中的过期信息
        Long[] demandinfo = serverDao.selectDemandPastinfo();
        for (int i = 0; i < demandinfo.length; i++) {
            serverDao.deleteDemandinfo(demandinfo[i].intValue());
            //同时删除订单表中的相关信息
            serverDao.deleteOrderDemandInfo(demandinfo[i].toString());
        }
        //查看服务列表中的过期信息
        Long[] serverinfo = serverDao.selectServerPastinfo();
        for (int i = 0; i < serverinfo.length; i++) {
            serverDao.deleteServerinfo(serverinfo[i].intValue());
            serverDao.deleteOrderServerinfo(serverinfo[i].intValue());
        }
        //查看待确认订单
        List<Map<String, Object>> lists = serverDao.selectConfirmedOrder();
        for (int i = 0; i < lists.size(); i++) {
            Date date = (Date) lists.get(i)
                    .get("server_time");
            int flag = serverDao.selectIsPushServer((Integer) lists.get(i)
                    .get("id"));
            if (date.getTime() < System.currentTimeMillis() && flag == 0) {
                AuroraPush.pushTargetForDriver(lists.get(i)
                        .get("server_user_id")
                        .toString(), "您有一条服务即将开始，请前往服务地点");
                //将该订单标记已推送
                serverDao.insertPushOrder((Integer) lists.get(i)
                        .get("id"), 1);
            }
        }
        //查看初始状态的需求订单
        List<Map<String, Object>> arrayList = serverDao.selectOriginalState();
        for (int i = 0; i < arrayList.size(); i++) {
            Date time = serverDao.selectFristApplyTime(arrayList.get(i)
                    .get("server_id")
                    .toString());
            int flag = serverDao.selectIsPushDemand((Integer) arrayList.get(i)
                    .get("id"));
            if (time != null && time.getTime() < System.currentTimeMillis() && flag == 0) {
                AuroraPush.pushTargetForDriver(arrayList.get(i)
                        .get("user_id")
                        .toString(), "您当前需求有新的报名人，请及时确认");
                //将该订单标记已推送
                serverDao.insertPushOrder((Integer) arrayList.get(i)
                        .get("id"), 2);
            }
        }
    }

    /**
     * 查看ping++ 账单记录
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void withdraw() {
        Pingpp.apiKey = "sk_live_LCyvz9HyvjbTKqTGOG9WHGGO";
        Pingpp.privateKey = PingCons.privateKey;
        List<Withdraw> withdraws = userDao.selectWithdrawList();
        if(withdraws.size()>0){
        	  for (Withdraw withdraw : withdraws) {		
        		  try {
					Transfer transfer = Transfer.retrieve(withdraw.getOrder_id());
					if(transfer.getStatus().equals("paid")){
						userDao.updateWithdraw("提现成功", null, withdraw.getId()+"");
						Map<String,Object> map = new HashMap<>();
						map.put("money", withdraw.getMoney());
						map.put("userid", withdraw.getUser_id());
						userDao.updateUserWallet(map);
						// 获取用户余额
						String selectUserMoney = userDao.selectUserMoney(withdraw.getUser_id());
						String s = userDao.selectUserMoney("1");
						userDao.insertMessqge(withdraw.getUser_id(), "你发起的提现已经到账", "3", withdraw.getId()+"");		
						serverDao.insertCancelOrder(withdraw.getUser_id(), withdraw.getMoney()+"", "提现成功", withdraw.getWithdrawal_order(), selectUserMoney, "2", s+"", null);
					}else if(transfer.getStatus().equals("failed")){
						// 获取用户余额
						String selectUserMoney = userDao.selectUserMoney(withdraw.getUser_id());
						userDao.insertMessqge(withdraw.getUser_id(), "你发起的提现失败，请重新提交", "6", withdraw.getId()+"");		
						userDao.updateWithdraw("审核不通过",transfer.getFailureMsg(),withdraw.getId()+"");	
						serverDao.insertCancelOrder(withdraw.getUser_id(), withdraw.getMoney()+"", "提现失败", withdraw.getWithdrawal_order(), selectUserMoney, "2", null, null);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} 
      		}
        }
    }

    public static void main(String[] args) {
        Pingpp.apiKey = "sk_live_LCyvz9HyvjbTKqTGOG9WHGGO";
        Pingpp.privateKey = PingCons.privateKey;
        try {
            Transfer transfer = Transfer.retrieve("tr_bv1vn988C4K00q1yf9SirzDyH");
            System.out.println(transfer);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        } catch (InvalidRequestException e) {
            e.printStackTrace();
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIException e) {
            e.printStackTrace();
        } catch (ChannelException e) {
            e.printStackTrace();
        } catch (RateLimitException e) {
            e.printStackTrace();
        }

    }
}
